﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AnesthesiaSys.HardwareControlModule
{
    public class ComPrinterDataSender : IPrinterDataSender, IDisposable
    {
        private SerialPort _serialPort;

        public void Init()
        {
            if (_serialPort == null)
            {

                _serialPort = new SerialPort("COM5");

                // SerialPort 4.0 有很多预先设置好的枚举项，是不是很容易？！
                //_serialPort.Parity = Parity.None;
                //_serialPort.DataBits = 8;
                //_serialPort.StopBits = StopBits.One;
                //_serialPort.Handshake = Handshake.RequestToSend;

                _serialPort.Encoding = Encoding.GetEncoding("GBK");

                // Set the read/write timeouts
                _serialPort.ReadTimeout = 500;
                _serialPort.WriteTimeout = 500;

                //_serialPort.RtsEnable = true;
                _serialPort.DtrEnable = true;   // Epson TM 打印机出场默认都是DTR/DSR，非常重要！！

                _serialPort.BaudRate = 9600;//115200;
                
                _serialPort.Open();
                _serialPort.DataReceived += _serialPort_DataReceived;
            }
        }

        private void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            var com = sender as SerialPort;
            var buffer = new byte[com.BytesToRead];
            com.Read(buffer, 0, buffer.Length);
            Console.WriteLine(BitConverter.ToString(buffer));

        }

        public void SendData2Printer(byte[] data)
        {
            _serialPort.Write(data, 0, data.Length);
        }

        public void Dispose()
        {
            if (_serialPort != null)
            {
                _serialPort.Dispose();
                _serialPort = null;
            }
        }
    }
}
